package com.cupcorn.onlinescript;

import java.util.ArrayList;
import org.andengine.engine.Engine.EngineLock;
import org.json.JSONException;
import org.json.JSONObject;
import android.widget.Toast;
import com.cupcorn.balapkarung.GameDefine;
import com.cupcorn.balapkarung.state.StateHighscore;
import com.cupcorn.balapkarung.state.StateHighscoreOnline;
import com.cupcorn.balapkarung.state.StateMainMenu;
import com.cupcorn.lib.Utils;
import com.cupcorn.lib.game.GameEngine;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class OnlineScript extends ServerConfiguration
{
	public static boolean isConnect;
	public static ObjectScoring object[] = new ObjectScoring[OBJECT_SCORING_COUNT];
	
	public static void checkConnection()
	{	
		AsyncHttpClient client = new AsyncHttpClient();
		client.post(SERVER+DELIMETER+DIR+DELIMETER+SCRIPT_EXAMPLE, new AsyncHttpResponseHandler()
			{
				public void onSuccess(String response) 
				{
					isConnect = true;
					GameEngine.instance().ToastMakeText(1, response, Toast.LENGTH_LONG);
				};
				public void onFailure(Throwable e) 
				{
					isConnect = false;
					GameEngine.instance().ToastMakeText(1, e.getMessage(), Toast.LENGTH_LONG);
				};
			}
		);
	}
	
	public static void sendData(ObjectScoring object)
	{
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams postData = new RequestParams();
		postData.put("data", object.toJsonString());
		client.post(SERVER+DELIMETER+DIR+DELIMETER+SERVER_GET_DATA, postData, new AsyncHttpResponseHandler()
			{
				public void onSuccess(String response) 
				{
					GameEngine.instance().ToastMakeText(1,"success "+ response, Toast.LENGTH_LONG);
					Utils.TRACE(response);
				};
				
				public void onFailure(Throwable e) 
				{
					GameEngine.instance().ToastMakeText(1, "error "+e.getMessage(), Toast.LENGTH_LONG);
				};
			}
		);
	}
	
	public static void get_ObjectsScoring(ObjectScoring object)
	{
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams postData = new RequestParams();
		postData.put("data", object.toJsonString());
		client.post(SERVER+DELIMETER+DIR+DELIMETER+SERVER_GET_OBJECT_SCORING, postData, new AsyncHttpResponseHandler()
			{
				public void onSuccess(String response)
				{
					GameEngine.instance().ToastMakeText(1,"success "+ response, Toast.LENGTH_LONG);
					Utils.TRACE(response);
					generate_objects(response);
					StateMainMenu.waitForOnlineGameplay = false;
					StateMainMenu.onlineGameplayReady = true;
					GameEngine.instance().ToastMakeText(1, "Gameplay Online Ready", Toast.LENGTH_SHORT, true);
				};
				public void onFailure(Throwable e) 
				{
					StateMainMenu.waitForOnlineGameplay = false;
					StateMainMenu.notOnlineForGameplay = true;
					GameEngine.instance().ToastMakeText(1, "You are not online", Toast.LENGTH_SHORT, true);
					GameEngine.instance().ToastMakeText(1, "error "+e.getMessage(), Toast.LENGTH_LONG);
					Utils.TRACE("error "+e.getMessage());
				};
			}
		);
	}
	
	public static void get_TopScores()
	{
		AsyncHttpClient client = new AsyncHttpClient();
		GameEngine.instance().ToastMakeText(1, "Please wait, retrieving data Online", Toast.LENGTH_LONG, true);
		client.post(SERVER+DELIMETER+DIR+DELIMETER+SERVER_GET_HIGHSCORES, new AsyncHttpResponseHandler()
			{
				public void onSuccess(String response)
				{
					StateHighscore.highscoreOnlineReady = true;
					GameEngine.instance().ToastMakeText(1,"success "+ response, Toast.LENGTH_LONG);
					Utils.TRACE(response);
					generate_top_scores(response);
				};
				public void onFailure(Throwable e) 
				{
					StateHighscore.highscoreNotOnline = true;
					GameEngine.instance().ToastMakeText(1, "error "+e.getMessage(), Toast.LENGTH_LONG);
					GameEngine.instance().ToastMakeText(1, "You're not online, please check your connection", Toast.LENGTH_LONG, true);
				};
			}
		);
	}

	public static void generate_objects(String value)
	{
		String objectString[] = value.split("#");
		JSONObject objects[] = new JSONObject[OBJECT_SCORING_COUNT];
		for(int i = 0; i < objects.length; i++)
		{
			try 
			{
				objects[i] = new JSONObject(objectString[i]);
			} 
			catch (JSONException e) 
			{
				e.printStackTrace();
			}
		}
		for(int i = 0; i < object.length; i++)
		{
			try 
			{
				object[i] = new ObjectScoring(objects[i].getString("id"), objects[i].getString("array"), objects[i].getInt("score"));
				Utils.TRACE("==========="+i);
				Utils.TRACE(object[i].getName());
				Utils.TRACE(object[i].getScore());
				Utils.TRACE(object[i].getArrayValue_().toString());
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void generate_top_scores(String response)
	{
		String objectString[] = response.split("#");
		EngineLock lock = GameEngine.instance().getEngine().getEngineLock();
		lock.lock();
		StateHighscoreOnline.displaySprite.getSprite(GameDefine.ONLINE_YOURRANK).detachSelf();
		lock.unlock();
		boolean isInTopFive = false;
		int pos = GameDefine.ONLINE_NAMESCORE_1;
		for(int i = 0; i < objectString.length; i++)
		{
			StateHighscoreOnline.displayText.text[i].setText(objectString[i]);
			if(Utils.getUsername().equals(objectString[i]))
			{
				isInTopFive = true;
				StateHighscoreOnline.setRank(pos);
			}
			if(i%2==0)
				pos++;
		}
		if(isInTopFive)
		{
			StateHighscoreOnline.ungenerateOwnScores();
		}
		else
		{
			StateHighscoreOnline.generateOwnScores();
		}
	}
	
	@Deprecated
	public static ArrayList<Integer> returnArray;
	
	@Deprecated
	public static void getData()
	{
		AsyncHttpClient client = new AsyncHttpClient();
		
		client.post("http://dwiprabowo.com/balapkarung/get.php", new AsyncHttpResponseHandler()
			{
				public void onSuccess(String response)
				{
					GameEngine.instance().ToastMakeText(1,"success "+ response, Toast.LENGTH_LONG);
					returnArray = stringToArrayList(response);
				};
				
				public void onFailure(Throwable e) 
				{
					GameEngine.instance().ToastMakeText(1, "error "+e.getMessage(), Toast.LENGTH_LONG);
				};
			}
		);
	}
	
	@Deprecated
	public static String arrayListToString(ArrayList<Integer> listJump)
	{
		String mapping = "";
		for(int i = 0; i < listJump.size(); i++)
		{
			mapping += "&"+listJump.get(i);
		}
		
		if(listJump == stringToArrayList(mapping))
		{
			GameEngine.instance().ToastMakeText(1, "SAMA BRO", Toast.LENGTH_LONG);
		}
		
		return mapping;
	}
	
	@Deprecated
	public static ArrayList<Integer> stringToArrayList(String data)
	{
		String[] result = data.split("&");
		ArrayList<Integer> value = new ArrayList<Integer>();
		
		for(int i = 0; i < result.length; i++)
		{
			if(i == 0)continue;
			value.add(Integer.parseInt(result[i]));
		}
		
		return value;
	}
	
	@Deprecated
	public static void get_TopHighscoreOnline()
	{
		AsyncHttpClient client = new AsyncHttpClient();
		
		client.post("http://dwiprabowo.com/balapkarung/getnew.php", new AsyncHttpResponseHandler()
			{
				public void onSuccess(String response)
				{
					GameEngine.instance().ToastMakeText(1,"success "+ response, Toast.LENGTH_LONG);
					Utils.TRACE(response);
					generate_objects(response);
				};
				
				public void onFailure(Throwable e) 
				{
					GameEngine.instance().ToastMakeText(1, "error "+e.getMessage(), Toast.LENGTH_LONG);
				};
			}
		);
	}
}